package com.zjitc.chapter12.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjitc.chapter12.domain.Product;
import com.zjitc.chapter12.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
public class DataController {
    @RequestMapping("/showDataByResponse")
    public void showDataByResponse(HttpServletResponse response) {
        try {
            response.getWriter().write("response");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/showDataByJson")
    public void showDataByJson(HttpServletResponse response) {
        System.out.println("DataController.showDataByJson");
        User user = new User();
        user.setPassword("123556");
        user.setUsername("zjitc");
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            response.getWriter().print(objectMapper.writeValueAsString(user));
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/getUser")
    @ResponseBody
    public User getUser() {
        System.out.println("DataController.getUser");
        User user = new User();
        user.setPassword("123556");
        user.setUsername("zjitc");
        return user;
    }
    @RequestMapping("/addProducts")
    @ResponseBody
    public List<Product> addProducts() {
        List<Product> products = new ArrayList<>();
        Product product = new Product();
        product.setId(1);
        product.setName("iphone");
        products.add(product);
        product = new Product();
        product.setId(2);
        product.setName("ipad");
        products.add(product);
        return products;
    }
}
